import React, {ErrorInfo, Suspense, useEffect} from "react";
import {createRoot} from "react-dom/client";
import {ErrorBoundary} from "react-error-boundary";
import {useTranslation} from "react-i18next";
import {syncThemeWithLocal} from "./helpers/theme_helpers";
import {updateAppLanguage} from "./helpers/language_helpers";
import SuspenseFallback from "./pages/suspense-fallback";
import {RouterProvider} from "react-router-dom";
import router from "@/router";
import {useAsyncEffect} from "ahooks";
import "./localization/i18n";

/**
 * 回退渲染
 * @param error
 * @param resetErrorBoundary
 */
function fallbackRender({error, resetErrorBoundary}: any) {
  return (
    <div role="alert">
      <p>出错了:</p>
      <pre style={{color: "red"}}>{error.message}</pre>
      <button onClick={resetErrorBoundary}>点击重试</button>
    </div>
  );
}

// 错误上报函数
function logErrorToService(error: Error, info: ErrorInfo) {
  console.error("Caught an error:", error, info);
}

export default function App() {
  const {i18n} = useTranslation();

  useAsyncEffect(async () => {
    await syncThemeWithLocal();
    await updateAppLanguage(i18n);
  }, [i18n]);

  return (
    <ErrorBoundary
      fallbackRender={fallbackRender}
      onError={logErrorToService}
    >
      <Suspense fallback={<SuspenseFallback/>}>
        <RouterProvider future={{v7_startTransition: true}} router={router}/>
      </Suspense>
    </ErrorBoundary>
  );
}

const root = createRoot(document.getElementById("app")!);
root.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
);
